from wsgiref.simple_server import make_server
import wsgiref.util
import os
import pdb

import MSConfig;    c = MSConfig.config()
import MSLogger;    l = MSLogger.configure('wsgi_server')
import MSDatabase
db = MSDatabase.Database(c.get('main', 'dbpath'))
MSDatabase.instance = db
import MSMethods;   m = MSMethods.MethodHandler()
import MSWSGIPatterns as w
import MSUser

# PAGES
def handle_page(data, cookie): return w.Common.getHead() + w.Common.getTopbar(cookie) + data + w.Common.getFoot()

def handle_textload(contenttype, environ, start_response):
    name    = wsgiref.util.shift_path_info(environ)
    if not w.checkName(name): 
        l.info('handle_textload: 404 on name %s', name)
        return w.Common.get404(start_response, name)
    fname   = c.get('main', contenttype) + name
    if not w.checkFile(fname):
        l.info('handle_textload: 404 on file %s', fname)
        return w.Common.get404(start_response, name)

    f = open(fname, 'r')
    w.Common.putHeader(start_response, 200, [(contenttype, 'text')])
    return [f.read()]

def handle_imageload(contenttype, environ, start_response):
    name    = wsgiref.util.shift_path_info(environ)
    if not w.checkName(name): 
        l.info('handle_imageload: 404 on name %s', name)
        return w.Common.get404(start_response, name)
    fname   = c.get('main', contenttype) + name
    if not w.checkFile(fname): 
        l.info('handle_imageload: 404 on file %s', fname)
        return w.Common.get404(start_response, name)
    try:
        spl = fname.split('.')
        ext = spl[len(spl) - 1]
    except:
        l.info('handle_imageload: 404 on file ext %s', fname)
        return w.Common.get404(start_response, name)

    f = open(fname, 'r')
    w.Common.putHeader(start_response, 200, [(ext, contenttype)])
    return [f.read()]


# APPLICATION
def mymethod(environ, start_response, cookie):
    mname = wsgiref.util.shift_path_info(environ)
    try:
        hdl = getattr(m, mname)
        return hdl(environ, start_response, cookie)
    except AttributeError:
        w.Common.putHeader(start_response, 400, [('html', 'text')])
        return ['not_found']

def myapp(environ, start_response):
    cookie = MSUser.cookie(environ)
    rqtype = wsgiref.util.shift_path_info(environ)
    if len(rqtype) == 0: 
        rqtype='method'
        if environ.has_key('QUERY_STRING') and environ['QUERY_STRING'].find('mainContentFrame') != -1:
            environ['PATH_INFO'] = '/process_alarm_form'
        else:
            environ['PATH_INFO'] = '/login'

    try:
        if rqtype == 'method':
            res = mymethod(environ, start_response, cookie)
            if str(type(res)).find('tuple') != -1:
                ret = handle_page(res[0], cookie)
                ret[0] = ret[0].replace('<!--META_REDIRECT-->',
                                        '<meta http-equiv="refresh" content="2; url=%s">' % res[1])
                return ret
            return handle_page(res, cookie)
        if rqtype == 'rawmethod':       return mymethod(environ, start_response, cookie)
        if rqtype == 'html':            return handle_page(handle_textload(rqtype, environ, start_response), cookie)
        if rqtype in ['css', 'js']:     return handle_textload(rqtype, environ, start_response)
        if rqtype == 'image':           return handle_imageload(rqtype, environ, start_response)
        if rqtype == 'favicon.ico':     return handle_imageload('image', {'PATH_INFO' : '/favicon.ico'}, start_response)

        return handle_page(w.Common.get404(start_response, rqtype), cookie)
    except Exception, err:
        l.error('rqtype(%s): %s', rqtype, str(err))
        try:
            w.Common.putHeader(start_response, 400, [('html', 'text')])
        except AssertionError, headerError:
            l.error('rqtype(%s): AssertionError: %s', rqtype, str(headerError))
        finally:
            return ['failed']

##########################
if __name__ == "__main__":
    from wsgiref.simple_server import make_server
    import wsgiref.util
    MSDatabase.getInstance().start()
    MSDatabase.getInstance().setAutoUpdate(180)

    httpd = make_server(c.get('main','host'), int(c.get('main','port')), myapp)
    l.info("Serving HTTP at %s:%s...", c.get('main','host'), c.get('main','port'))
    try:
        httpd.serve_forever()
    except KeyboardInterrupt, err:
        l.info('Server gracefull shutdown')
    except Exception, err:
        l.error('Server fatal error: %s', str(err))
    finally:
        MSDatabase.getInstance().stop()
